#include "qwcombboxdelegate.h"
#include<QComboBox>

QWCombBoxDelegate::QWCombBoxDelegate(QStyledItemDelegate *parent)
    : QStyledItemDelegate{parent}
{}

QWidget *QWCombBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QComboBox* pComb = new QComboBox(parent);
    // 设置无边框
    pComb->setFrame(false);
    for(int i=0;i < m_strItems.count() ; i++)
    {
        pComb->addItem(m_strItems.at(i));
    }

    pComb->setEditable(m_bEdit);
    return pComb;
}

void QWCombBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    // 从数据模型获取值,显示到代理组件中
    QString strText = index.model()->data(index,Qt::EditRole).toString();
    QComboBox* pCombo = static_cast<QComboBox*>(editor);
    pCombo->setCurrentText(strText);
}

void QWCombBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    // 从代理组件中获取值,设置到数据模型中
    QComboBox* pCombo = static_cast<QComboBox*>(editor);
    QString strText = pCombo->currentData().toString();
    model->setData(index,strText,Qt::EditRole);

}

void QWCombBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

void QWCombBoxDelegate::setItems(QStringList strList, bool bEdit)
{
    m_strItems = strList;
    m_bEdit = bEdit;
}
